/**
 * 导出面板组件
 */

import React, { useState } from 'react';
import { Download, FileText, FileSpreadsheet, Check, ArrowLeft } from 'lucide-react';
import { useProofMapper } from '@/contexts/ProofMapper';
import { useBusiness } from '@/stores/useBusinessStore';
import { showMessage } from '@/components/common/MessageTip';
import type { ExportFormat, ExportConfig } from '@/types/ProofMapper';
import { exportProofMapperToWord, exportProofMapperToExcel } from './utils/exportUtils';
import { getAssessmentTypeName } from '@/utils/utils';

interface ExportPanelProps {
  className?: string;
}

// 导出格式说明
export const exportFormatDescriptions = {
  word: {
    title: 'Word 文档',
    subtitle: '格式化表格文档',
    description: '适合文档归档和正式提交'
  },
  excel: {
    title: 'Excel 表格',
    subtitle: '可编辑电子表格',
    description: '便于后续编辑和数据处理'
  }
};


const ExportPanel: React.FC<ExportPanelProps> = ({ className = '' }) => {
  const {
    exportConfig,
    isVersionSaved,
    sortedItems,
    selectedItems,
    selectedItemsCount,
    setExportConfig,
    setLoading,
    createVersion
  } = useProofMapper();
  const { selectedBusiness } = useBusiness();

  const [isExporting, setIsExporting] = useState(false);
  const [showPreview, setShowPreview] = useState(false);
  const [showSavePanel, setShowSavePanel] = useState(false);
  const [versionName, setVersionName] = useState('');

  // 处理导出配置更改
  const handleConfigChange = (key: keyof ExportConfig, value: any) => {
    setExportConfig({
      ...exportConfig,
      [key]: value
    });
  };

  // 处理导出操作
  const handleExport = async () => {
    if (!isVersionSaved) {
      showMessage('warning', '请先保存当前版本后再导出');
      return;
    }
    
    const itemsToExport = exportConfig.selected_items_only 
      ? sortedItems.filter(item => selectedItems.includes(item.id))
      : sortedItems;

    if (itemsToExport.length === 0) {
      showMessage('warning', '没有可导出的项目');
      return;
    }

    setIsExporting(true);
    setLoading(true);

    try {
      // 根据选择的格式进行导出
      if (exportConfig.format === 'word') {
        const fileName = selectedBusiness 
          ? `${selectedBusiness.name}_${getAssessmentTypeName(selectedBusiness.assessmentType)}_安全评估证明材料收集清单`
          : '安全评估证明材料收集清单';
        exportProofMapperToWord(
          itemsToExport,
          fileName,
          {
            includeNotes: exportConfig.include_notes,
            includeSummary: exportConfig.include_summary,
            pageBreakAfterModule: false // 可以根据需要添加配置选项
          }
        );
      } else if (exportConfig.format === 'excel') {
        const fileName = selectedBusiness 
          ? `${selectedBusiness.name}_${getAssessmentTypeName(selectedBusiness.assessmentType)}_安全评估证明材料收集清单`
          : '安全评估证明材料收集清单';
        exportProofMapperToExcel(
          itemsToExport,
          fileName,
          {
            includeNotes: exportConfig.include_notes,
            includeSummary: exportConfig.include_summary
          }
        );
      }

      showMessage('success', `导出成功！共导出 ${itemsToExport.length} 个项目`);
      
    } catch (error) {
      showMessage('error', '导出失败，请重试');
      console.error('Export error:', error);
    } finally {
      setIsExporting(false);
      setLoading(false);
    }
  };

  // 获取格式图标
  const getFormatIcon = (format: ExportFormat) => {
    switch (format) {
      case 'word':
        return <FileText className="h-8 w-8 text-blue-500" />;
      case 'excel':
        return <FileSpreadsheet className="h-8 w-8 text-green-500" />;
      default:
        return <FileText className="h-8 w-8 text-gray-500" />;
    }
  };

  // 计算导出项目数量
  const exportItemsCount = exportConfig.selected_items_only 
    ? selectedItemsCount 
    : sortedItems.length;

  // 计算导出模块数量
  const exportModulesCount = (() => {
    const base = exportConfig.selected_items_only
      ? sortedItems.filter(item => selectedItems.includes(item.id))
      : sortedItems;
    return new Set(base.map(item => item.module)).size;
  })();

  if (showPreview) {
    return (
      <div className={`space-y-6 ${className}`}>
        {/* 预览标题 */}
        <div className="bg-white/80 dark:bg-card backdrop-blur-sm rounded-lg border border-border p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-3">
              <div className="flex items-center justify-center w-10 h-10 bg-orange-500/10 rounded-lg">
                <FileText className="h-5 w-5 text-orange-500" />
              </div>
              <div>
                <h2 className="text-lg font-semibold text-foreground">清单预览</h2>
                <p className="text-sm text-muted-foreground">
                  预览即将导出的证明材料清单
                </p>
              </div>
            </div>
            <button
              onClick={() => setShowPreview(false)}
              className="inline-flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
            >
              <ArrowLeft className="h-4 w-4" />
              返回设置
            </button>
          </div>

          {/* 预览统计 */}
          <div className="grid grid-cols-4 gap-4 mb-6">
            <div className="text-center">
              <div className="text-2xl font-bold text-primary">{exportItemsCount}</div>
              <div className="text-sm text-muted-foreground">评估项总数</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-green-600">{exportModulesCount}</div>
              <div className="text-sm text-muted-foreground">评估模块</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-orange-600">0</div>
              <div className="text-sm text-muted-foreground">重点项目</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-gray-600">0</div>
              <div className="text-sm text-muted-foreground">已选择导出</div>
            </div>
          </div>
        </div>

        {/* 预览内容 */}
        <div className="bg-white/80 dark:bg-card backdrop-blur-sm rounded-lg border border-border overflow-hidden">
          <div className="bg-muted/50 px-6 py-3 border-b border-border">
            <h3 className="text-lg font-semibold text-foreground">
              安全评估证明材料收集清单
            </h3>
            <p className="text-sm text-muted-foreground">
              生成时间：{new Date().toLocaleString()}
            </p>
          </div>

          <div className="p-6">
            {/* 汇总信息 */}
            {exportConfig.include_summary && (
              <div className="mb-6">
                <h4 className="text-md font-semibold text-foreground mb-3">汇总信息</h4>
                <div className="bg-muted/25 rounded-lg p-4">
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-muted-foreground">评估项总数：</span>
                      <span className="font-medium">{exportItemsCount} 项</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">涉及模块：</span>
                      <span className="font-medium">{exportModulesCount} 个</span>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* 详细清单 */}
            <div>
              <h4 className="text-md font-semibold text-foreground mb-3">详细清单</h4>
              <div className="overflow-x-auto">
                <table className="w-full border border-border">
                  <thead className="bg-muted/50">
                    <tr>
                      <th className="px-4 py-2 text-left text-sm font-medium border-b border-border">序号</th>
                      <th className="px-4 py-2 text-left text-sm font-medium border-b border-border">评估模块</th>
                      <th className="px-4 py-2 text-left text-sm font-medium border-b border-border">查验点</th>
                      <th className="px-4 py-2 text-left text-sm font-medium border-b border-border">所需证明材料</th>
                      {exportConfig.include_notes && (
                        <th className="px-4 py-2 text-left text-sm font-medium border-b border-border">备注</th>
                      )}
                    </tr>
                  </thead>
                  <tbody>
                    {(exportConfig.selected_items_only 
                      ? sortedItems.filter(item => selectedItems.includes(item.id))
                      : sortedItems
                    ).slice(0, 5).map((item, index) => (
                      <tr key={item.id} className="border-b border-border">
                        <td className="px-4 py-2 text-sm">{index + 1}</td>
                        <td className="px-4 py-2 text-sm">{item.module}</td>
                        <td className="px-4 py-2 text-sm">{item.checkpoint}</td>
                        <td className="px-4 py-2 text-sm">{item.materials}</td>
                        {exportConfig.include_notes && (
                          <td className="px-4 py-2 text-sm text-muted-foreground">{item.notes}</td>
                        )}
                      </tr>
                    ))}
                  </tbody>
                </table>
                {exportItemsCount > 5 && (
                  <div className="text-center py-4 text-sm text-muted-foreground">
                    ... 还有 {exportItemsCount - 5} 项（完整内容将在导出文件中显示）
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* 导出按钮 */}
        <div className="flex justify-center">
          <button
            onClick={handleExport}
            disabled={isExporting}
            className="inline-flex items-center gap-2 px-6 py-3 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isExporting ? (
              <>
                <div className="w-4 h-4 border-2 border-primary-foreground/30 border-t-primary-foreground rounded-full animate-spin" />
                正在导出...
              </>
            ) : (
              <>
                <Download className="h-4 w-4" />
                确认导出
              </>
            )}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className={`space-y-6 ${className}`}>
      {/* 导出设置 */}
      <div className="bg-white/80 dark:bg-card backdrop-blur-sm rounded-lg border border-border p-6">
        <div className="flex items-center gap-3 mb-6">
          <div className="flex items-center justify-center w-10 h-10 bg-orange-500/10 rounded-lg">
            <Download className="h-5 w-5 text-orange-500" />
          </div>
          <div>
            <h2 className="text-lg font-semibold text-foreground">导出功能</h2>
            <p className="text-sm text-muted-foreground">
              导出评估清单为不同格式的文档
            </p>
          </div>
          {/* 顶部右侧：保存当前版本按钮 */}
          <div className="ml-auto">
            <button
              type="button"
              className="inline-flex items-center gap-2 px-3 py-2 text-sm bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
              onClick={() => setShowSavePanel(v => !v)}
            >
              + 保存当前版本
            </button>
          </div>
        </div>

        {/* 保存版本面板（展开/折叠） */}
        {showSavePanel && (
          <div className="mb-6 rounded-lg border border-border bg-muted/30 p-4">
            <div className="text-sm font-medium text-foreground mb-2">版本名称</div>
            <input
              value={versionName}
              onChange={(e) => setVersionName(e.target.value)}
              placeholder="例如：网络安全基础版本 v1.0"
              className="w-full px-3 py-2 rounded-md border border-border bg-background text-foreground mb-3"
            />
            <div className="text-xs text-muted-foreground mb-3">
              每次保存都会创建新版本，不会覆盖已有版本
            </div>
            <div className="flex items-center gap-3">
              <button
                type="button"
                className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
                onClick={async () => {
                  const name = versionName.trim();
                  if (!name) {
                    showMessage('warning', '请填写版本名称');
                    return;
                  }
                  
                  const ok = await createVersion(selectedBusiness?.assessmentType || '', name);
                  if (ok) {
                    setVersionName('');
                    setShowSavePanel(false);
                  }
                }}
              >
                确认保存
              </button>
              <button
                type="button"
                className="px-4 py-2 rounded-md hover:bg-muted"
                onClick={() => setShowSavePanel(false)}
              >
                取消
              </button>
            </div>
          </div>
        )}

        {/* 导出格式选择 */}
        <div className="mb-6">
          <h3 className="text-md font-semibold text-foreground mb-3">选择导出格式</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {Object.entries(exportFormatDescriptions).map(([format, info]) => (
              <div
                key={format}
                onClick={() => handleConfigChange('format', format as ExportFormat)}
                className={`
                  p-4 border rounded-lg cursor-pointer transition-all
                  ${exportConfig.format === format 
                    ? 'border-primary bg-primary/5' 
                    : 'border-border hover:border-primary/50'
                  }
                `}
              >
                <div className="flex items-center gap-3 mb-2">
                  {getFormatIcon(format as ExportFormat)}
                  <div className="flex-1">
                    <h4 className="font-medium text-foreground">{info.title}</h4>
                    <p className="text-sm text-muted-foreground">{info.subtitle}</p>
                  </div>
                  {exportConfig.format === format && (
                    <Check className="h-5 w-5 text-primary" />
                  )}
                </div>
                <p className="text-xs text-muted-foreground">{info.description}</p>
              </div>
            ))}
          </div>
        </div>

        {/* 导出选项 */}
        <div className="mb-6">
          <h3 className="text-md font-semibold text-foreground mb-3">导出选项</h3>
          <div className="space-y-3">
            <label className="flex items-center gap-3">
              <input
                type="checkbox"
                checked={exportConfig.include_notes}
                onChange={(e) => handleConfigChange('include_notes', e.target.checked)}
                className="rounded border-input"
              />
              <span className="text-sm text-foreground">包含备注信息</span>
            </label>
            
            <label className="flex items-center gap-3">
              <input
                type="checkbox"
                checked={exportConfig.include_summary}
                onChange={(e) => handleConfigChange('include_summary', e.target.checked)}
                className="rounded border-input"
              />
              <span className="text-sm text-foreground">包含汇总统计</span>
            </label>
            
            <label className="flex items-center gap-3">
              <input
                type="checkbox"
                checked={exportConfig.selected_items_only}
                onChange={(e) => handleConfigChange('selected_items_only', e.target.checked)}
                className="rounded border-input"
              />
              <span className="text-sm text-foreground">
                仅导出选中项目 ({selectedItemsCount} 项已选中)
              </span>
            </label>
          </div>
        </div>

        {/* 导出说明 */}
        <div className="bg-muted/50 rounded-lg p-4 mb-6">
          <h4 className="text-sm font-medium text-foreground mb-2">导出说明：</h4>
          <ul className="text-xs text-muted-foreground space-y-1">
            <li>• <strong>Word：</strong> 适合文档归档和正式提交</li>
            <li>• <strong>Excel：</strong> 便于后续编辑和数据处理</li>
          </ul>
        </div>

        {/* 操作按钮 */}
        <div className="flex items-center justify-between">
          <button
            onClick={() => setShowPreview(true)}
            disabled={exportItemsCount === 0}
            className="inline-flex items-center gap-2 px-4 py-2 text-sm text-primary hover:bg-primary/10 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <FileText className="h-4 w-4" />
            预览清单
          </button>
          
          <button
            onClick={handleExport}
            disabled={isExporting || exportItemsCount === 0 || !isVersionSaved}
            className="inline-flex items-center gap-2 px-6 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isExporting ? (
              <>
                <div className="w-4 h-4 border-2 border-primary-foreground/30 border-t-primary-foreground rounded-full animate-spin" />
                导出中...
              </>
            ) : (
              <>
                <Download className="h-4 w-4" />
                立即导出{!isVersionSaved ? '（请先保存版本）' : ''}
              </>
            )}
          </button>
        </div>
      </div>

      {/* 统计信息（本地实时计算，避免统计对象为空导致全为0） */}
      <div className="bg-white/80 dark:bg-card backdrop-blur-sm rounded-lg border border-border p-6">
        <h3 className="text-lg font-semibold text-foreground mb-4">统计信息</h3>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="text-center">
            <div className="text-2xl font-bold text-primary">{sortedItems.length}</div>
            <div className="text-sm text-muted-foreground">评估项总数</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-green-600">{new Set(sortedItems.map(i => i.module)).size}</div>
            <div className="text-sm text-muted-foreground">评估模块</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-orange-600">0</div>
            <div className="text-sm text-muted-foreground">重点项目</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-gray-600">{exportItemsCount}</div>
            <div className="text-sm text-muted-foreground">已选择导出</div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ExportPanel;
